﻿using AutoMapper;
using Dm;
using ERPPublic;
using ERPPublic.eneity;
using FinancialManagement.Application.Command.SaleContractCommand;
using FinancialManagement.Domain.Dto.SaleContract;
using FinancialManagement.Domain.Model;
using FinancialManagement.Dtos;
using FinancialManagement.Infrstructre.Interface;
using Google.Protobuf.Collections;
using MediatR;
using Newtonsoft.Json;
using SqlSugar;
using System.IO.Pipelines;
using static ERPPublic.ParseAPI;

namespace FinancialManagement.Application.CommandHandler.SaleContractCommandHandlers
{
    public class SaleContractShowCommandHandlers : IRequestHandler<SaleContractShowCommand, PageDto<SaleContractShowDto>>
    {
        IMapper mapper;
        private readonly ISaleContractProductRepository SRep;
        private readonly ISaleContractRepository CRep;
        ISqlSugarClient db;

        public SaleContractShowCommandHandlers(IMapper mapper, ISaleContractProductRepository SRep, ISaleContractRepository CRep, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.SRep = SRep;
            this.CRep = CRep;
            this.db = db;
        }
        public async Task<PageDto<SaleContractShowDto>> Handle(SaleContractShowCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductList("", "", 1, 1000);
            var list = (from a in await CRep.GetAllAsyns() select a).Where(x => x.IsDel == false).ToList();
            var item = (from b in await SRep.GetAllAsyns() select b).ToList();
            var result = (from c in list
                          select new SaleContractShowDto
                          {
                              SaleContractId=c.SaleContractId,
                              ClientId=c.ClientId,
                              ClientName=c.ClientName,
                              SCAgencyDate=c.SCAgencyDate,
                              ContractTopic=c.ContractTopic,
                              SCcontractNumber=c.SCcontractNumber,
                              SCStartDate=c.SCStartDate,
                              SCEndDate=c.SCEndDate,
                              SCPeople=c.SCPeople,
                              SCCountpartPeople=c.SCCountpartPeople,
                              SCContractType=c.SCContractType,
                              SCSalespeopleId= c.SCSalespeopleId,
                              SCSalespeople=c.SCSalespeople,
                              DocumentMakers=c.DocumentMakers,
                              DocumentTime=c.DocumentTime,
                              SCcontractPrice=c.SCcontractPrice,
                              SCPreferentialPrice=c.SCPreferentialPrice,
                              PreferentialPrice=c.PreferentialPrice,
                              SundryPrice=c.SundryPrice,
                              SCReceivPeople=c.SCReceivPeople,
                              SCRePhone=c.SCRePhone,
                              ProvinceId=c.ProvinceId,
                              CityId=c.CityId,
                              SCAddress=c.SCAddress,
                              SCNum=c.SCNum,
                              SCTax=c.SCTax,
                              PreProductionId=c.PreProductionId,
                              RelevancyId=c.RelevancyId,
                              RelevancyIName=c.RelevancyIName,
                              SCOutState=c.SCOutState,
                              SCShipmentState=c.SCShipmentState,
                              AddName = c.AddName,
                              AddTime = c.AddTime,
                              UpdName = c.UpdName,
                              UpdTime = c.UpdTime,
                              DelName = c.DelName,
                              DelTime = c.DelTime,
                              IsDel = c.IsDel,
                              Office_Id = c.Office_Id,
                              User_Id = c.User_Id,
                              SaleContractProductDto = (from d in item
                                                        join e in products on d.ProductId equals e.ProductId
                                                       where d.SCcontractNumber==c.SCcontractNumber
                                                       select new SaleContractProducts
                                                       {
                                                         SaleContractProductId=d.SaleContractProductId,
                                                           SCcontractNumber=d.SCcontractNumber,
                                                           ProductId=d.ProductId,
                                                           PName=d.PName,
                                                           PNumber=d.PNumber,
                                                           SCPNum=d.SCPNum,
                                                           TaxPrice=d.TaxPrice,
                                                           Discount=d.Discount,
                                                           BillType=d.BillType,
                                                           DetailsPreferential=d.DetailsPreferential,
                                                           TaxLines=d.TaxLines,
                                                           DeliveryTime=d.DeliveryTime,
                                                           SRemark=d.SRemark,
                                                           SInventory=d.SInventory,
                                                           PSpec=e.PSpec,
                                                           PUnit=e.PUnit,
                                                           AddName =d.AddName,
                                                           AddTime=d.AddTime,
                                                           UpdName=d.UpdName,
                                                           UpdTime=d.UpdTime,
                                                           DelName=d.DelName,
                                                           DelTime=d.DelTime,
                                                           IsDel=d.IsDel,
                                                           Office_Id=d.Office_Id,
                                                           User_Id=d.User_Id,

                                                       }).ToList()


                          });
            if(!string.IsNullOrEmpty(request.ContractTopic))
            {
                result = result.Where(x => x.ContractTopic.Contains(request.ContractTopic));
            }
            if (!string.IsNullOrEmpty(request.RelevancyIName))
            {
                result = result.Where(x => x.RelevancyIName.Contains(request.RelevancyIName));
            }
            if (!string.IsNullOrEmpty(request.ContractTopic))
            {
                result = result.Where(x => x.ClientName.Contains(request.ClientName));
            }
            if (request.STime != null||request.ETime!=null)
            {
                result = result.Where(x => request.STime <= x.SCAgencyDate && x.SCAgencyDate <= request.ETime);
            }
            if (!string.IsNullOrEmpty(request.SCSalespeople))
            {
                result = result.Where(x => x.SCSalespeople.Contains(request.SCSalespeople));
            }
            if (!string.IsNullOrEmpty(request.SCcontractNumber))
            {
                result = result.Where(x => x.SCcontractNumber.Contains(request.SCcontractNumber));
            }




            PageDto<SaleContractShowDto> page = new PageDto<SaleContractShowDto>();
            // 执行查询并获取总数  
            page.lcount = result.Count();
            page.pcount = (int)Math.Ceiling(page.lcount * 1.0 / request.PageSize);
            page.list = result.OrderByDescending(t => t.SaleContractId).Select(t => mapper.Map<SaleContractShowDto>(t)).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return page;;
        }



        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="PName"></param>
        /// <param name="PNumber"></param>
        /// <param name="pindex"></param>
        /// <param name="psize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetProductList(string? PName, string? PNumber, int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/erpcp/api/Product/ProductShow?PName=" + PName + "&PNumber=" + PNumber + "&ProductTypeId=" + 0 + "&PageIndex=" + pindex + "&PageSize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }


        //产品
        public class Products
        {
            /// <summary>
            /// 产品Id
            /// </summary>
            [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
            public int ProductId { get; set; }
            /// <summary>
            /// 标识
            /// </summary>

            public int? PCharacteristic { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PNumber { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PName { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PSpec { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PUnit { get; set; }

            /// <summary>
            /// 产品分类ID
            /// </summary>

            public int ProductTypeId { get; set; }




        }





    }





}
